package com.glodon.paas.account.web.util;

import java.util.Map;
import java.util.concurrent.ExecutorService;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.velocity.VelocityEngineUtils;

public class Mail {
	private JavaMailSender javaMailSender;
	private VelocityEngine velocityEngine;
	private String from;
	private String title;
	private String encoding;
	private String templateLocation;
	
	@Autowired
	private ExecutorService execotor;

	/**
	 * send email synchronously
	 * @param model
	 * @param toEmails
	 */
	public void send(Map<String, Object> model,String[] toEmails) {
		try {
			MimeMessage msg = buildMessage(model, toEmails);
			javaMailSender.send(msg);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * send email in asynchronous manner
	 * @param model
	 * @param toEmails
	 */
	public void sendAsync(Map<String, Object> model,String[] toEmails) {
		try {
			final MimeMessage msg = buildMessage(model, toEmails);
			execotor.execute(new Runnable() {
				@Override
				public void run() {
					javaMailSender.send(msg);
				}
			});
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	private MimeMessage buildMessage(Map<String, Object> model, String[] toEmails) throws MessagingException {
		MimeMessage msg = javaMailSender.createMimeMessage();
		MimeMessageHelper message = new MimeMessageHelper(msg, true, encoding);
		message.setFrom(from);
		message.setSubject(title);
		message.setTo(toEmails);
		String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateLocation, encoding, model);
		message.setText(text, true);
		return msg;
	}

	public void setJavaMailSender(JavaMailSender javaMailSender) {
		this.javaMailSender = javaMailSender;
	}
	
	public JavaMailSender getSender() {
		return javaMailSender;
	}

	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public void setTemplateLocation(String templateLocation) {
		this.templateLocation = templateLocation;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public void setFrom(String from) {
		this.from = from;
	}
}
